//
//  HomeController.m
//  CMJWeibo
//
//  Created by BH on 15/12/4.
//
//

#import "HomeController.h"
#import "NavMiddleButton.h"
#import "NavTitleMenu.h"
#import "UIView+MJ.h"
#import "UIImage+MJ.h"
#import "UIBarButtonItem+MJ.h"
#import "AccountTool.h"
#import "UserInfoParam.h"
#import "UserTool.h"
#import <MJRefresh/MJRefresh.h>
#import "CMJCommon.h"
#import "HomeStatusParam.h"
#import "StatusFrame.h"
#import "StatusModel.h"
#import "StatusTool.h"
#import "HomeCell.h"
#import "DetailController.h"

@interface HomeController ()

@property(nonatomic,strong)NavMiddleButton *middleBtn;
@property(nonatomic,strong)NavTitleMenu *titleMenu;
@property(nonatomic,strong)NSMutableArray *statusArr;//微博数据

@end

@implementation HomeController

#pragma mark - 初始化
-(NavMiddleButton *)middleBtn
{
    if (!_middleBtn) {
        self.middleBtn = [[NavMiddleButton alloc] init];
    }
    return _middleBtn;
}

-(NavTitleMenu *)titleMenu
{
    if (!_titleMenu) {
        self.titleMenu = [[NavTitleMenu alloc] init];
        self.titleMenu.width = 200;
        self.titleMenu.height = 200;
        self.titleMenu.centerX = self.view.width * 0.5;
        self.titleMenu.y = 55;
    }
    return _titleMenu;
}

-(NSMutableArray *)statusArr
{
    if (!_statusArr) {
        self.statusArr = [NSMutableArray array];
    }
    return _statusArr;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置导航栏
    [self setupNav];
    
    //添加刷新控件
    [self setupRefresh];
    
    //获取用户个人信息
    [self getUserInfo];
}

/**
 *  设置导航栏
 */
-(void)setupNav
{
    // 中间的标题按钮
    NSString *name = [AccountTool account].name;
    [self.middleBtn setTitle:name?name:@"首页" forState:UIControlStateNormal];
    [self.middleBtn setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [self.middleBtn setHeight:38];
    [self.middleBtn addTarget:self action:@selector(middleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = self.middleBtn;
    
    // 左右的按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendSearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"" highImage:@"" target:self action:@selector(pop)];
}

/**
 *  导航栏中间按钮点击事件
 */
-(void)middleBtnClick:(NavMiddleButton *)sender
{
    NSLog(@"NavmiddleBtnClick");
    UIImage *downImg = [UIImage imageWithName:@"navigationbar_arrow_down"];
    UIImage *upImg = [UIImage imageWithName:@"navigationbar_arrow_up"];
    
    if (sender.currentImage == downImg) {
        [sender setImage:upImg forState:UIControlStateNormal];
        // 弹出菜单
        [self.view.window addSubview:self.titleMenu];
        self.titleMenu.alpha = 0;
        
        [UIView animateWithDuration:0.5 animations:^{
            self.titleMenu.alpha = 1;
        }];
        
        self.tableView.scrollEnabled = NO;
        
    }else{
        
        [sender setImage:downImg forState:UIControlStateNormal];
        // 隐藏菜单
        [UIView animateWithDuration:0.5 animations:^{
            self.titleMenu.alpha = 0;
        } completion:^(BOOL finished) {
            [self.titleMenu removeFromSuperview];
        }];
        self.tableView.scrollEnabled = YES;
    }
}

/**
 *  导航栏左边按钮点击事件
 */
-(void)friendSearch
{
    NSLog(@"friendSearch");
}

/**
 *  导航栏右边按钮点击事件
 */
-(void)pop
{
    NSLog(@"pop");
}

/**
 *  添加刷新控件
 */
-(void)setupRefresh
{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreStatus)];
    
    //设置tableview
    self.tableView.backgroundColor = GlobalBGColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, CellMargin, 0);
}

/**
 *  刷新
 */
-(void)loadNewStatus
{
    //清空badgeValue
    self.tabBarItem.badgeValue = nil;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    HomeStatusParam *param = [HomeStatusParam param];
    // 取出最前面的那条微博
    StatusFrame *statusF = [self.statusArr firstObject];
    // 加载微博ID比status.idstr大的微博数据
    if (statusF) {
        param.since_id = @(statusF.status.idstr.longLongValue);
    }
    
    //获得微博数据
    [StatusTool homeStatusWithParam:param success:^(HomeStatusResult *result) {
        //将StatusModel转成StatusFrame
        NSMutableArray *newStatusF = [NSMutableArray array];
        for (StatusModel *status in result.statuses) {
            StatusFrame *frame = [[StatusFrame alloc] init];
            frame.status = status;
            [newStatusF addObject:frame];
        }
        
        // 创建一个临时数组
        NSMutableArray *tempArr = [NSMutableArray array];
        // 添加最新的模型数据
        [tempArr addObjectsFromArray:newStatusF];
        // 追加以前的旧模型数据
        [tempArr addObjectsFromArray:self.statusArr];
        // 将临时数组赋值给 以前的大数组
        self.statusArr = tempArr;
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
        // 提示最新微博的数量
        [self showNewStatusCount:result.statuses.count];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
        [self.tableView.mj_header endRefreshing];
    }];
}

/**
 *  提示最新微博的数量
 */
-(void)showNewStatusCount:(NSInteger)count
{
    // 添加label到navigationBar的下面
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithName:@"timeline_new_status_background"]];
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    //设置文字
    if (count) {
        label.text = [NSString stringWithFormat:@"共有%ld条新的微博数据",count];
    } else {
        label.text = @"没有新的微博数据";
    }
    
    //设置frame
    label.width = self.navigationController.view.width;
    label.height = 35;
    label.x = 0;
    label.y = 64-label.height;
    label.alpha = 0;
    
    //动画显示与消失
    [UIView animateWithDuration:0.5 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
        label.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
            label.transform = CGAffineTransformIdentity;
            label.alpha = 0;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

/**
 *  更多
 */
-(void)loadMoreStatus
{
    HomeStatusParam *param = [HomeStatusParam param];
    //取出最后面的那条微博
    StatusFrame *statusF = [self.statusArr lastObject];
    if (statusF) {
        param.max_id = @(statusF.status.idstr.longLongValue - 1);
    }
    
    [StatusTool homeStatusWithParam:param success:^(HomeStatusResult *result) {
        NSMutableArray *newStatusF = [NSMutableArray array];
        for (StatusModel *model in result.statuses) {
            StatusFrame *frame = [[StatusFrame alloc] init];
            frame.status = model;
            [newStatusF addObject:frame];
        }
        
        [self.statusArr addObjectsFromArray:newStatusF];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
        [self.tableView.mj_footer endRefreshing];
    }];
}

/**
 *  获取用户个人信息
 */
-(void)getUserInfo
{
    UserInfoParam *param = [UserInfoParam param];
    param.uid = [AccountTool account].uid;
    
    [UserTool getUserInfoWithParam:param success:^(UserInfoResult *result) {
        
        //设置导航栏中间按钮文字
        [self.middleBtn setTitle:result.name forState:UIControlStateNormal];
        
        //存储昵称
        Account *account = [AccountTool account];
        account.name = result.name;
        [AccountTool saveAccount:account];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

-(void)refreshFromOther:(BOOL)fromOther
{
    if (self.tabBarItem.badgeValue) {
        //有新的微博
        [self.tableView.mj_header beginRefreshing];
    }else if (fromOther == NO){
        //没有新的数据
        NSIndexPath *fristRow = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView scrollToRowAtIndexPath:fristRow atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

#pragma mark - tableview datasource & delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statusArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCell *cell = [HomeCell cellWithTableView:tableView];
    cell.statusF = self.statusArr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.tabBarItem.badgeValue = nil;
    DetailController *detail = [[DetailController alloc] init];
    detail.statusF = self.statusArr[indexPath.row];
    [self.navigationController pushViewController:detail animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StatusFrame *statusF = self.statusArr[indexPath.row];
    return statusF.cellHeight;
}

@end
